package com.zsy.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

public class TestRegexServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			resp.setCharacterEncoding("utf-8");
			String url = req.getParameter("url");
			String regex = req.getParameter("regex");
			int type = Integer.parseInt(req.getParameter("type"));
			String encode = req.getParameter("encode");
			if(null == encode){
				encode = "gb2312";
			}
			MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
			HttpConnectionManagerParams params = connectionManager.getParams();
			params.setConnectionTimeout(5000);
			params.setSoTimeout(20000);
			params.setDefaultMaxConnectionsPerHost(32);// very important!!
			params.setMaxTotalConnections(5000);// very important!!
			GetMethod method = new GetMethod(url);
			HttpClient client = new HttpClient();
			client.executeMethod(method);
			InputStream in = method.getResponseBodyAsStream();
			// 这里使用8859-1读取
			BufferedReader br = new BufferedReader(new InputStreamReader(in,
					"ISO-8859-1"));
			String tempbf;
			StringBuffer content = new StringBuffer(1000);
			// while读流中的内容，并在过程中获取编码方式
			while ((tempbf = br.readLine()) != null) {
				content.append(tempbf + "\n");
			}
			String response =  new String(content.toString().getBytes("ISO-8859-1"), encode);
			System.out.println(regex);
			System.out.println(response);
			Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE
					| Pattern.MULTILINE|Pattern.DOTALL);
			Matcher m = p.matcher(response);
			StringBuilder sb = new StringBuilder();
			while(m.find()){
				sb.append(m.group(type));
				sb.append("\n");
				sb.append(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
			}
			if(sb.length()>0){
				resp.getWriter().print(sb.toString());
			}else{
				resp.getWriter().print("对不起，没有符合条件的结果，请重新配置");
			}
			
		}catch(Exception e){
			resp.getWriter().print("正则配置有问题；可能原因是分组配置部分");
		}
		
	}

}
